import 'package:bike_ride/common/util/hysize_fit.dart';
import 'package:bike_ride/common/widget/page_title_widget.dart';
import 'package:bike_ride/common/widget/super_button_widget.dart';
import 'package:bike_ride/res/style/color_styles.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter_plus/webview_flutter_plus.dart';
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';

class WebViewPage extends StatefulWidget {
  /// url\content\bottomWidget [HtmlBottomWidget]
  final Map<String, dynamic> arguments;

  const WebViewPage({
    Key? key,
    required this.arguments,
  }) : super(key: key);

  @override
  State<WebViewPage> createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  late WebViewControllerPlus controller;
  String? _title;

  //是否显示撤销操作
  bool isShowCancel = false;
  @override
  initState() {
    super.initState();

    // if (Platform.isAndroid) WebView.platform = AndroidWebView();
    isShowCancel = widget.arguments['isShowCancel'] == true;
    controller = WebViewControllerPlus()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: _onLoadingProgress,
          onPageStarted: (String url) {},
          onPageFinished: _onPageFinished,
          onHttpError: (HttpResponseError error) {},
          onWebResourceError: (WebResourceError error) {},
          onNavigationRequest: (NavigationRequest request) {
            print('test webView跳转地址：${request.url}');
            if(request.url.startsWith('http')){
              return NavigationDecision.navigate;
            }else{
              _openUrl('linkaja://linkaja.id/applink/payment?data=OnoFlXNvQBbS_8pk6BTZdy15j8uoX0I9khjjLIPYeINhexzxiMS8nYIR-ZRCZSP_iJ2kk68c0EzQ2LSfGlkOyrRf0Fih6jWwAptgxXpVwFtTOyXRY0AQGDFlwmjaea0iMNdzkwf6abKqO61N1YQTRFl1OQOrPrJAXNkBkxRUOtHZD9aAewF5zJCG4yXJ6oRVMap_3YQ2B1vhHVtWzuf4B6Ek6p0uDWXkUlThv_MgXGUXASvgfc8oazjDB3pwvrp-t1n_uvR16hmV07Z9FC7roIPmA3eKC_ieSl3ZnIyVh9mSp98y0R-sPcBdB8Ahf-Ja0cWHEiVc1nFVkg-4IoIa8elOSyT8grvav-4SdFYwo62lkTwKczDg65s_q28vX6wC9D7sEvSM8ANU06Sl2Co3wn1KPJTB71sYi8q94XbhxP-J_L6Y0GrEHwgoMXMaUTPEl0kINq8DbveCRJ8lDuJJOgxJQmgQuTf1qeLY9TG8xYEpatvYRpSYw4mekTK6Cw1nk2cI');
              return NavigationDecision.prevent;
            }
          },
        ),
      )
      ..loadRequest(Uri.parse(widget.arguments['url']));
  }

  Future<void> _openUrl(String linkUrl) async {
    await launch(linkUrl).catchError((error){
      print('test catch $error');
      /// error:PlatformException(ACTIVITY_NOT_FOUND, No Activity found to handle intent { linkaja://linkaja
      if(error.toString().contains('ACTIVITY_NOT_FOUND')){
        EasyLoading.showToast('ACTIVITY_NOT_FOUND',toastPosition: EasyLoadingToastPosition.bottom);
      }
    });
  }

  @override
  dispose() {
    if(EasyLoading.isShow){
      EasyLoading.dismiss();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      backgroundColor: ColorStyles.color_F3F4F5,
      body: Column(
        children: [
          PageTitleWidget(title: _title ?? ''),
          Expanded(
            child: Stack(
              children: [
                WebViewWidget(
                  controller: controller,
                ),
                if(widget.arguments['bottomWidget'] != null)
                  Align(alignment: Alignment.bottomCenter,child: widget.arguments['bottomWidget'],)
              ],
            ),
          ),
        ],
      ),
    );
  }

  _onPageFinished(String url) async {
    EasyLoading.dismiss();
    final title = await controller.getTitle();
    if (mounted) {
      setState(() {
        _title = title;
      });
    }
  }

  _onLoadingProgress(num progress) {
    EasyLoading.showProgress(progress/100);
  }
}

class HtmlContent extends StatelessWidget {
  /// title\content\bottomWidget [HtmlBottomWidget]
  final Map<String, dynamic> arguments;

  const HtmlContent({super.key, required this.arguments});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      backgroundColor: ColorStyles.color_F3F4F5,
      body: Column(
        children: [
          PageTitleWidget(title: arguments['title'],),
          Expanded(child: SingleChildScrollView(
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 16.rpx),
              child: HtmlWidget(
                arguments['content'],
                customStylesBuilder: (element) {
                  // if (element.classes.contains('foo')) {
                  //   return {'color': 'red'};
                  // }
                  return null;
                },

                customWidgetBuilder: (element) {
                  // if (element.attributes['foo'] == 'bar') {
                  //   return FooBarWidget();
                  // }
                  //
                  // if (element.attributes['fizz'] == 'buzz') {
                  //   return InlineCustomWidget(
                  //     child: FizzBuzzWidget(),
                  //   );
                  // }

                  return null;
                },

                // onTapUrl: (url) => print('tapped $url'),
                // consider using `ListView` or `SliverList` for better performance
                renderMode: RenderMode.column,
                // set the default styling for text
                textStyle: TextStyle(fontSize: 14),
              ),
            ),
          )),
          if(arguments['bottomWidget'] != null)
            arguments['bottomWidget']
        ],
      ),
    );
  }
}


class HtmlBottomWidget extends StatelessWidget {
  final Function() onPressed;
  final String btnText;

  const HtmlBottomWidget({super.key, required this.onPressed, required this.btnText});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.rpx,vertical: 22.rpx),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(topLeft: Radius.circular(16.rpx),topRight: Radius.circular(16.rpx)),
        color: ColorStyles.color_FFFFFF,
        boxShadow: [
          BoxShadow(
            color: ColorStyles.color_000000.withOpacity(0.05),
            blurRadius: 16,
            offset: const Offset(0, -8),
          ),
        ],
      ),
      child: SuperButtonWidget(
        btnText: btnText,
        onPressed: onPressed,
        bgColor: ColorStyles.color_F3F4F5,
        textColor: Theme.of(context).colorScheme.primary,
      )
    );
  }
}
